package org.gongliang.common.base;

import java.beans.PropertyEditorSupport;
import java.sql.Timestamp;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import org.gongliang.common.shiro.ShiroUser;
import org.gongliang.common.web.StringEscapeEditor;
import org.gongliang.kit.DateKit;
import org.gongliang.kit.web.ShiroKit;
import org.gongliang.kit.web.WebKit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ui.Model;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;

/**
 * 
 * @Description 基础控制器
 * @author 龚亮
 * @date 2017年3月30日 下午5:17:01
 */
public abstract class BaseController {

	public static final Logger logger = LoggerFactory.getLogger(BaseController.class);

	@InitBinder
	public void init(ServletRequestDataBinder binder) {
		// String类型转换，将所有传递进来的String进行HTML编码，防止XSS攻击、sql注入
		binder.registerCustomEditor(String.class, new StringEscapeEditor(true, false, true));

		/**
		 * 自动转换日期类型的字段格式
		 */
		// Date 类型转换
		binder.registerCustomEditor(Date.class, new PropertyEditorSupport() {
			@Override
			public void setAsText(String text) {
				setValue(DateKit.parseDate(text));
			}
		});
		// Timestamp 类型转换
		binder.registerCustomEditor(Timestamp.class, new PropertyEditorSupport() {
			@Override
			public void setAsText(String text) {
				Date date = DateKit.parseDate(text);
				setValue(date == null ? null : new Timestamp(date.getTime()));
			}
		});
	}

	@ModelAttribute
	public final void initModel(HttpServletRequest request, Model model) {
		logger.error("request请求参数:" + WebKit.getParams(request));
		logger.error("http header:" + WebKit.getheaders(request));
	}

	public ShiroUser getUser() {
		return ShiroKit.getLoginUser();
	}

	public Long getUserId() {
		return null == ShiroKit.getLoginUser() ? null : ShiroKit.getLoginUser().getId();
	}
}
